const express = require('express');
const router = express.Router();
const { FileHandler } = require('../utils/fileHandler');
const { validateToken } = require('../middleware/auth');
const { IPChecker } = require('../utils/ipChecker');
const rateLimit = require('express-rate-limit');

const fileHandler = new FileHandler();

// IP请求频率限制
const ipLimiter = rateLimit({
    windowMs: 15 * 60 * 1000, // 15分钟
    max: 100, // 限制每个IP 100个请求
    message: { error: '请求过于频繁，请稍后再试' }
});

// 添加一个测试路由
router.get('/api/test', (req, res) => {
    res.json({ message: '路由正常工作' });
});

// 获取最新IP记录
router.get('/api/get_latest_ips', async (req, res) => {
    try {
        const data = await fileHandler.readIpData();
        if (!data || data.length === 0) {
            return res.json({
                ipv4: [],
                ipv6: [],
                timestamp: ""
            });
        }
        res.json(data[data.length - 1]);
    } catch (error) {
        res.status(500).json({ error: '获取数据失败' });
    }
});

// 上报IP - 添加IP过滤
router.post('/api/get_ip', ipLimiter, validateToken, async (req, res) => {
    try {
        // 过滤并验证IP
        const [publicIPv4s, publicIPv6s] = await IPChecker.filterPublicIPs(
            req.body.ipv4 || [],
            req.body.ipv6 || []
        );

        const timestamp = new Date().toISOString();
        
        // 只有存在公网IP时才保存
        if (publicIPv4s.length > 0 || publicIPv6s.length > 0) {
            const ipData = {
                ipv4: publicIPv4s,
                ipv6: publicIPv6s,
                timestamp
            };
            
            await fileHandler.appendIpData(ipData);
            console.log(`[${timestamp}] IP已更新 (IPv4: ${publicIPv4s.length}, IPv6: ${publicIPv6s.length})`);
            
            res.json({ 
                status: "success",
                message: "公网IP地址已记录",
                data: ipData
            });
        } else {
            console.log(`[${timestamp}] 未发现公网IP`);
            res.json({
                status: "warning",
                message: "未发现可用的公网IP地址",
                data: {
                    ipv4: [],
                    ipv6: [],
                    timestamp
                }
            });
        }
    } catch (error) {
        console.error('IP数据处理失败:', error);
        res.status(500).json({ error: '保存数据失败' });
    }
});

module.exports = router; 